package com.engc.common.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import jxl.Sheet;

import org.apache.commons.lang.StringUtils;

import com.engc.common.bean.SysUserInfo;
import com.engc.common.service.BaseService;

public class BaseUtils {
	public static boolean isEmpty(Object object) {
		return object == null || ((String) object).length() < 1;
	}

	/**
	 * 判断是否是Equals
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static boolean isEquals(Object a, Object b) {
		if (a == b)
			return true;
		return a == null ? b.equals(a) : a.equals(b);
	}

	/**
	 * 获取成功信息
	 * 
	 * @param IsError
	 * @param Message
	 * @param data
	 * @return
	 */
	public static Map<String, Object> getSuccessMessage(boolean IsError, String Message, Object data) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("IsError", IsError);
		map.put("Message", Message);
		map.put("Data", data);
		return map;
	}

	/**
	 * 
	 * @param Message
	 * @param data
	 * @return
	 */
	public static Map<String, Object> getSuccessMessage(String Message, Object data) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("IsError", false);
		map.put("Message", Message);
		map.put("Data", data);
		return map;
	}

	public static Map<String, Object> getSuccessMessage(String Message) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("IsError", false);
		map.put("Message", Message);
		map.put("Data", null);
		return map;
	}
	
	//add by chenjianye
	public static Map<String, Object> getSuccessMessage(String Message, Map<String, Object> object){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("IsError", false);
		map.put("Message", Message);
		map.put("Data", object);
		return map;
	}
	
	public static Map<String, Object> getErrorMessage(String Message) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("IsError", true);
		map.put("Message", Message);
		return map;
	}

	/**
	 * 图片上传-获取失败信息
	 * 
	 * @param message
	 * @return
	 */
	public static String getError(String message) {
		String result ="{\"error\": 1, \"message\":\""+message+"\"}";
		return result;
	}
	
	/**
	 * 图片上传-获取成功信息
	 * 
	 * @param url
	 * @return
	 */
	public static String getSuccess(String url) {
		String result ="{\"error\": 0, \"url\":\""+url+"\"}";
		return result;
	}
	
	/**
	 * 获取服务器绝对路径 
	 * 
	 * @param relativePath ：工程下相当路径地址 例：uploadpic/student
	 * @return
	 */
	
	public static String getRealPath(String relativePath) throws Exception{
		String bastPath = BaseUtils.class.getResource("").getPath();
		bastPath = URLDecoder.decode(bastPath, "utf-8");// 
		String filePath = bastPath.substring(0, bastPath.indexOf("WEB-INF"));
		filePath = filePath.substring(1, filePath.length());
		String fullPath = filePath + relativePath;// 完整本地路径
		return fullPath;
	}
	
	/**
	 * 获取成功信息
	 * 
	 * @param data
	 * @return
	 */
	public static Map<String, Object> getSuccessMessage(Object data) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("IsError", false);
		map.put("Message", "");
		map.put("Data", data);
		return map;
	}

	public static Map<String, Object> getGridData(int Total, Object gridData) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Total", Total);
		map.put("Rows", gridData == null ? new ArrayList<Map<String, Object>>() : gridData);
		return map;
	}

	/**
	 * 从Request 请求中，解析Inset相关参数
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, Object> getInsertParam(HttpServletRequest request) {
		Map<String, Object> record = new HashMap<String, Object>();
		Enumeration<String> enume = request.getParameterNames();
		while (enume.hasMoreElements()) {
			String name = enume.nextElement().toString();
			if (!BaseUtils.isEmpty(request.getParameter(name))) {
				record.put(name, request.getParameter(name));
			}
		}
		return record;
	}

	public static Map<String, Object> getUpdateParam(HttpServletRequest request, String... removeParam) {
		Map<String, Object> record = new HashMap<String, Object>();
		Enumeration enume = request.getParameterNames();
		while (enume.hasMoreElements()) {
			String name = enume.nextElement().toString();
			boolean istrue = false;
			for (int i = 0; i < removeParam.length; i++) {
				if (name.equalsIgnoreCase(removeParam[i])) {
					istrue = true;
					continue;
				}
			}
			if (!istrue) {
				record.put(name, request.getParameter(name));
			}
		}
		return record;
	}

	/**
	 * 将List 数组转换为Tree 所需要的数据
	 * 
	 * @param list
	 * @param id
	 *            ID 列
	 * @param pid
	 *            PID 列
	 * @return
	 */
	public static List<Map<String, Object>> ArrayToTreeData(List<Map<String, Object>> mydata, String id, String pid) {
		Map<Object, Object> h = new HashMap<Object, Object>();// 数据索引
		List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();// 数据池，返回的数据

		for (Map<String, Object> item : mydata) {
			if (!item.containsKey(id)) {
				continue;
			} else {
				h.put(item.get(id), item);
			}
		}

		for (Map<String, Object> item : mydata) {
			if (!item.containsKey(id)) {
				continue;
			}
			if (!item.containsKey(pid) || (item.get(pid) == null) || !h.containsKey(item.get(pid))) {
				r.add(item);
			} else {
				Map<String, List<Map<String, Object>>> pitem = (Map<String, List<Map<String, Object>>>) h.get(item.get(pid));
				if (!pitem.containsKey("children")) {
					List<Map<String, Object>> children = new ArrayList<Map<String, Object>>();
					children.add(item);
					pitem.put("children", children);
				} else {
					List<Map<String, Object>> children = pitem.get("children");
					children.add(item);
					pitem.put("children", children);
				}
			}
		}
		return r;
	}

	/**
	 * 从Session 中获取usrId
	 * 
	 * @param request
	 * @return
	 */
	public static String getUserCodeFromSession(HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		if (session.getAttribute(Constant.SYS_USER_INFO) != null) {
			SysUserInfo user = (SysUserInfo) session.getAttribute(Constant.SYS_USER_INFO);
			return user.getUsercode();
		}
		return "";
	}

	/**
	 * 获取当前登录信息
	 * 
	 * @param request
	 * @return
	 */
	public static SysUserInfo getCurrentUser(HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		if (session.getAttribute(Constant.SYS_USER_INFO) != null) {
			SysUserInfo user = (SysUserInfo) session.getAttribute(Constant.SYS_USER_INFO);
			return user;
		}
		return null;
	}

	/**
	 * 获取当前登录人所拥有的所有菜单
	 * 
	 * @param request
	 * @return
	 */
	public static List<Map<String, Object>> getUserMenus(BaseService baseService, HttpServletRequest request) {
		HttpSession session = request.getSession();
		SysUserInfo info = (SysUserInfo) session.getAttribute(Constant.SYS_USER_INFO);
		String sql = null;
		if (info.getMenuResource() == null) {
			
			
			sql = "select t1.*,t1.menuicon icon  from sys_menu t1 where t1.menuparentno='0' or t1.menuparentno is null ";
			List<Map<String, Object>> parentLs = baseService.Query(sql);

			//用户权限内button
			sql = "select t1.* from sys_button t1,sys_acl t2 where t2.privilegeaccess='sys_button' and t2.privilegemasterkey=? and t1.btnid=t2.privilegeaccesskey order by t1.seqno ";
			List<Map<String, Object>> buttonRows = baseService.Query(sql, info.getRoleid());
			
			//用户权限内menu
			sql = " select * from (" +
					"select t1.*,t1.menuicon icon from sys_menu  t1, sys_acl t2 where t2.privilegeaccess='sys_menu' and t2.privilegemasterkey=? and t2.privilegeaccesskey = t1.menuid " +
					" union " +
					" select t5.*,t5.menuicon icon from sys_menu t5 where exists (select 1 from (select t3.menuno from sys_button t3,sys_acl t4 where t4.privilegeaccess='sys_button' and t4.privilegemasterkey=? and t3.btnid=t4.privilegeaccesskey ) btnMenu where btnMenu.menuno=t5.menuno) " +
					")" +
					" order by menuorder asc";
			List<Map<String, Object>> menuRows = baseService.Query(sql, new Object[]{info.getRoleid(),info.getRoleid()});
			
			Map<String, ArrayList> buttonMap = new HashMap<String, ArrayList>();
			for (Map<String, Object> map : buttonRows) {
				if (buttonMap.containsKey(map.get("menuno"))) {
					buttonMap.get(String.valueOf(map.get("menuno"))).add(map);
				} else {
					ArrayList<Map<String, Object>> btLs = new ArrayList<Map<String, Object>>();
					btLs.add(map);
					buttonMap.put(String.valueOf(map.get("menuno")), btLs);
				}
			}

			List<Map<String, Object>> childrenLs = new ArrayList<Map<String, Object>>();

			for (Map<String, Object> map : menuRows) {
				if (map.get("menuparentno") != null && String.valueOf(map.get("menuparentno")).equals("0")) {
					//parentLs.add(map);
				} else {
					if(info.isLocked() && Constant.LOCK_MENU_LIST.contains(String.valueOf(map.get("menuno")))){
						continue;
					}
					childrenLs.add(map);
				}
			}

			String menuno = null;

			List<Map<String, Object>> children = null;
			Map<String, Object> parent = null;
			int len = parentLs.size();
			for (int i=len-1;i>=0;i--) {
				parent = parentLs.get(i);
				children = new ArrayList<Map<String, Object>>();
				menuno = (String) parent.get("menuno");
				for (Map<String, Object> map2 : childrenLs) {

					if (menuno.equals(String.valueOf(map2.get("menuparentno")))) {
						children.add(map2);
					}
				}
				if(children.isEmpty()){
					parentLs.remove(i);
				}else{
					parent.put("children", children);
				}
				
			}
			
			info.setMenuResource(parentLs);
			info.setMenuButtons(buttonMap);
		}
		return info.getMenuResource();
	}

	public static List<Map<String, Object>> getButtons(HttpServletRequest request, String menuNo) {
		HttpSession session = request.getSession(true);
		if (session.getAttribute(Constant.SYS_USER_INFO) != null) {
			SysUserInfo user = (SysUserInfo) session.getAttribute(Constant.SYS_USER_INFO);
			
			Map<String, ArrayList> allbuttons = user.getMenuButtons();
			return allbuttons.get(menuNo);
		}
		return null;
	}

	/**
	 * 字符MD5加密
	 * 
	 * @param str
	 *            需要加密的字符
	 * @return
	 */
	public static String MD5Encoding(String str) {
		try {
			byte[] strTemp = str.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			// md.update(strTemp);
			try {
				// 最重要的是这句,需要加上编码类型 保证中文加密结果
				md.update(str.getBytes("UTF-8"));
			} catch (UnsupportedEncodingException e) {
				md.update(str.getBytes());
			}
			return toHexString(md.digest());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 加密 算法
	 * 
	 * @param md
	 * @return 返回加密后字符
	 */
	private static String toHexString(byte[] md) {
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', };
		int j = hexDigits.length;
		char[] str = new char[j * 2];
		for (int i = 0; i < j; i++) {
			byte byteo = md[i];
			str[2 * i] = hexDigits[byteo >>> 4 & 0xf];
			str[2 * i + 1] = hexDigits[byteo & 0xf];
		}
		return new String(str);
	}

	/**
	 * MD5盐值加密
	 * 
	 * @param rawPass
	 *            密码
	 * @param salt
	 *            盐值
	 * @return
	 */
	public static String MD5Encoding(String rawPass, Object salt) {
		if (salt == null)
			return rawPass;
		return MD5Encoding(rawPass + "{" + salt.toString() + "}");
	}

	/**
	 * 获取访问的IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 资源地址补全
	 * 
	 * @param url
	 * @return
	 */
	public static String completePicUrl(Object url) {
		String temp;
		if (url == null || (url + "").equals("")) {
			return null;
		} else {
			temp = url + "";
		}
		String ip = new ReadProperties("config/fileserver.properties").getValue("ServerIp");
		String port = new ReadProperties("config/fileserver.properties").getValue("ServerPort");
		return "http://" + ip + ":" + port + temp;
	}
	
	
	public static FilterGroup getRuleGroup(FilterGroup oldrule, FilterGroup addRule) {

		FilterGroup dpRule = addRule;
		if (dpRule == null)
			return oldrule;
		FilterGroup resrule = new FilterGroup();
		resrule.setOp("and");
		List<FilterGroup> groups = new ArrayList<FilterGroup>();
		groups.add(oldrule);
		groups.add(dpRule);
		resrule.setGroups(groups);
		return resrule;
	}
	
	//去除空行
	public static int getRightRows(Sheet sheet) {
		int rsCols = sheet.getColumns(); // 列数
		int rsRows = sheet.getRows(); // 行数
		int nullCellNum;
		int afterRows = rsRows;
		for (int i = 1; i < rsRows; i++) { // 统计行中为空的单元格数
			nullCellNum = 0;
			for (int j = 0; j < rsCols; j++) {
				String val = sheet.getCell(j, i).getContents();
				val = StringUtils.trimToEmpty(val);
				if (StringUtils.isBlank(val))
					nullCellNum++;
			}
			if (nullCellNum >= rsCols) { // 如果nullCellNum大于或等于总的列数
				afterRows--; // 行数减一
			}
		}
		return afterRows;
	}
	
}
